<?php
require dirname(dirname(__FILE__)) . '/include/conf.php';
require dirname(dirname(__FILE__)) . '/include/basefunc.php';

// 读取抓数据开关
$errmsg_set = "Open config file error";
$set_str = conf_switch_sets('get');
if ($set_str == 'start'){
	unset($errmsg_set);
}elseif ($set_str == 'stop'){
	$errmsg_set = "Closed switch";
}
if (isset($errmsg_set)){
	print_log($errmsg_set);
}

// 本次抓取时间
if (!isset($argv[1]) || !is_numeric($argv[1])){
	print_log('Parameter error!');
}
$nowtimestamp = (int) $argv[1];
$nowtime = date('Y-m-d H:i:s', $nowtimestamp);

set_time_limit(30); // 超时时间30秒

$links = get_match_links();
if (!is_array($links)) {
	print_log('Link match failed:' . $links);
}

require dirname(dirname(__FILE__)) . '/include/database.php';
$cpids = array();
foreach ($links['links'] as $key => $link){
	$cpids[$key] = pcntl_fork();
	if ($cpids[$key] == -1){
		print_log('PHP fork failed');
	}elseif (!$cpids[$key]){
		/* ----------------子进程处理 begin---------------- */
		$all_match = $teams = $teams_id = array();
	    $data = request_by_curl_365($link, 10);
	    if (!$data){
	    	print_log('Request error:' . $link);
	    }
	    $sections = parse_item($data);
	    if (!empty($sections)){
	    	// 球队、时间、比分解析
	    	$match_time = $links['time'][$key];
	    	@list($home_team, $visiting_team) = explode(' v ', $links['teams'][$key]);

	    	foreach ($sections as $section){
		    	$section['match_time'] = $match_time;
		    	$section['home_team'] = $home_team;
		    	$section['visiting_team'] = $visiting_team;
		    	$section['fetch_time'] = $nowtime;
		    	$section['from'] = 1;
		    	$section['link'] = '';
		    	$section['match_name'] = '';
		    	$section['just'] = '';
		    	$section['match_id'] = 0;
		    	
		    	$teams[] = $home_team;
		    	$teams[] = $visiting_team;
		    	$all_match[] = $section;
	    	}
	    }
	    $teams = array_unique($teams);
	    
	    $db = db_touzhu();
	    if (!empty($teams)){
	    	// 读球队id，预留db中不存在的球队待入库
	    	$_teams = read_team_id($db, $teams, 1);
	    	if (!empty($_teams)){
	    		$teams = array_flip($teams);
	    		foreach ($_teams as $_team){
	    			$teams_id[$_team['team']] = $_team['bet365_id'];
	    			unset($teams[$_team['team']]);
	    		}
	    		$teams = array_flip($teams);
	    	}
	    
	    	// 球队写表
	    	if (!empty($teams)){
	    		$_teams_id = write_teams($db, $teams, 1);
	    		$teams_id = array_merge($teams_id, $_teams_id);
	    	}
	    
	    	foreach ($all_match as &$_item){
	    		$_item['home_team_id'] = isset($teams_id[$_item['home_team']]) ? $teams_id[$_item['home_team']] : 0;
	    		$_item['visiting_team_id'] = isset($teams_id[$_item['visiting_team']]) ? $teams_id[$_item['visiting_team']] : 0;
	    	}
	    }
	    
	    // 写数据库
	    if (!empty($all_match)){
	    	$re = write_ball_disc($db, $all_match);
	    	$re_str = '';
	    	if (isset($re['succ_match'])){
	    		$re_str .= 'Write ' . count($re['succ_match']) . ' successful';
	    	}
			if (isset($re['err_match'])){
				$re_str .= (empty($re_str) ? '' : ' &') . 'Write ' . count($re['err_match']) . 'failing';
			}
			print_log($re_str);
	    }else {
	    	$re = str_replace(array("\r\n", ' ', "\t"), '', strip_tags($data)) . "\t" . $link;
	    	print_log('Data match failed:' . $re);
	    }
	    
	    // 非常重要，不可删除
	    exit;
	    /* ----------------子进程处理 end---------------- */
	}
}

// 监控子进程状态，都执行完毕后继续往下执行
foreach ($cpids as $cpid){
	pcntl_waitpid($cpid, $status);
}

// 后续执行。。。


// 获取比赛地址
function get_match_links(){
	// 足球滚球盘url
	$url = 'https://mobile.28365365.com/sport/splash/Default.aspx?Sport=1&key=1&L=2&ip=1';
	$htmldata = request_by_curl_365($url);
    if (!$htmldata){
    	print_log('Request error:' . $url);
    }

	// 没有比赛时间的不匹配
    $link_regular = '/<div id="menuItem_[0-9]+" class="Level2"  > (.+)<\/div>/iU';
	preg_match_all($link_regular, $htmldata, $matches);
	if (!empty($matches[1])){
		$key = 0;
		$detail_regular = '/<a href="(.+)">(.+)<br\/><span class="Score">(.+)<\/span><span id="ct[0-9]+">(.+)<\/span><\/a>/iU';
		foreach ($matches[1] as $matche){
			preg_match_all($detail_regular, $matche, $_matches);
			if (!empty($_matches[0])){
				foreach ($_matches[0] as $_key => $_matche){
					$links[$key] = $_matches[1][$_key];
					$teams[$key] = $_matches[2][$_key];
					$score[$key] = $_matches[3][$_key];
					$time[$key] = $_matches[4][$_key];
					$key ++;
				}
			}
		}
		if ($key > 0){
			$find = array('..', 'ptid=0&amp;', '-2-0-0-1-1-');
			$replace = array('https://mobile.28365365.com/sport', 'clvl=2&', '-2-0-0-1-2-');
			$arr = array("Hello","world","!");
			$links = str_replace($find, $replace, $links);
			$re = array('links' => $links, 'teams' => $teams, 'score' => $score, 'time' => $time);
		}
	}
	$re = isset($re) ? $re : str_replace(array("\r\n", ' ', "\t"), '', strip_tags($htmldata));
	return $re;
}

// 解析数据项
function parse_item($htmldata){
    global $GLOBAL_WANFA_NUM;
    $arr = array();
    
    $items_regular = '/<div class="Section">(\r\n.+)*\r\n<\/div>\r\n\s+\r\n<\/div>/iU';
    preg_match_all($items_regular, $htmldata, $matches);
    if (!empty($matches[0])){
    	foreach ($matches[0] as $item){
    		$_item = explode("\r\n", trim(strip_tags($item)));
    		list($wanfa_str) = explode('(', $_item[0]);
    		list($wanfa_str) = explode('目前', $wanfa_str);
    		$wanfa_str = str_replace('附加', '', $wanfa_str);
    		
    		$wanfa = 0;
    		switch ($wanfa_str){
    			// 亚洲盘角球
    			//case $GLOBAL_WANFA_NUM[1]:
    			//	$wanfa = 1;
    			case $GLOBAL_WANFA_NUM[2]:
    				if ($wanfa == 0){
    					$wanfa = 2;
    				}
			    	@list($over) = explode('高于', $_item[2]);
			    	@list($under, $pankou) = explode('低于', $_item[3]);
		    		$pankou = trim($pankou);
	    			$over = trim($over);
	    			$under = trim($under);
	    			$arr[] = array(
	    				'wanfa' => $wanfa,
	    				'pankou' => $pankou,
	    				'over' => $over,
	    				'under' => $under
	    			);
    				break;
    				
    			// 大小盘
    			//case $GLOBAL_WANFA_NUM[3]:
    			//	$wanfa = 3;
    			case $GLOBAL_WANFA_NUM[4]:
    				if ($wanfa == 0){
    					$wanfa = 4;
    				}
    				foreach ($_item as $_tmp){
    					$_tmp_item = explode('高于', $_tmp);
    					if (count($_tmp_item) > 1){
    						$_arr = array('over' => trim($_tmp_item[0]));
    						$_pankou_sign = trim($_tmp_item[1]);
    						continue;
    					}
    					$_tmp_item = explode('低于', $_tmp);
    					$pankou = isset($_tmp_item[1]) ? trim($_tmp_item[1]) : '';
    					if (count($_tmp_item) > 1 && $_pankou_sign == $pankou){
    						$_arr['under'] = trim($_tmp_item[0]);
					    	if (strpos($pankou, ',') !== false){
					    		$_pankou = explode(',', $pankou);
					    		$pankou = round(($_pankou[0] + $_pankou[1]) / 2, 2);
					    	}
					    	$_arr['pankou'] = $pankou;
					    	$_arr['wanfa'] = $wanfa;
					    	$_arr['over'] = isset($_arr['over']) ? $_arr['over'] : '';
					    	$arr[] = $_arr;
    					}
    				}
			    	break;
    		}
    	}
    }
    return $arr;
}
